var Api = new function () {
    this.videoUrl = "http://117.172.164.150:82";
    var serverUrl = "http://117.172.164.150:82/WisdomPartyBuildingServices/api/";
    var serverUrlApi1 = "http://117.172.164.150:82/WisdomPartyBuildingServices/api/";
    //宜宾（测试）
    this.tci_id = this.TciId = "1";
    this.UnitGuid = "0053DEBF-10E6-4024-9311-BAD05AB25CA3";
    this.UnitPath = "3C65CD8B-5809-438C-8EB8-793EBAF4E5E1,9590ce74-d062-4696-a9b1-d16368f7c585,5d557ee7-5352-4bfb-a867-3ea271022d86,3db24930-5cdc-4c05-b0d5-4cce63c36deb";


    //验证控件 jquery.validate.js
    this.validate = function (element, options, isParams) {
        return $(element).validate($.extend({
            meta: "validate",
            ignore: [],
            onkeyup: false,
            onfocusin: false,
            onclick: false,
            onfocusout: false,//失去焦点不验证
            //errorPlacement: function (error, element) {
            //    if (element.attr("layerIndex") == undefined && error.text() != "") {
            //        var layerIndex = layer.tips(error.text(), element, { time: -1, tips: [3, '#ff0000'] });
            //        element.attr("layerIndex", layerIndex);
            //    }
            //},
            //success: function (label, element) {
            //    if ($(element).attr("layerIndex") != undefined) {
            //        layer.close($(element).attr("layerIndex"));
            //        $(element).removeAttr("layerIndex");
            //    }
            //},
            showErrors: function (errormap, errorlist) {
                //if (errorlist.length > 1) {
                //    errorlist.splice(1, errorlist.length - 1);
                //}
                //this.defaultShowErrors();

                $.each(errorlist, function (index, item) {
                    alert(item.message);
                    item.element.focus();
                    return false;
                });
                //return false;
            },
            submitHandler: function (form) {
                var $submitForm = $(form);
                var _url = $submitForm.attr("action");
                var _method = $submitForm.prop("method");
                var _data = Api.getWebControls(form);
                if (isParams) {
                    _data = { Params: _data };
                }
                Api.ajax({
                    url: _url,
                    data: _data,
                    type: _method,
                    dyejuri: false,
                    success: function (data) {
                        //$("input").val("");
                        //$("select").val("");
                        //$("textarea").val("");
                        //$(".ui-select").val("");
                        alert(data.Msg);
                    }
                })
            }
        }, options || {}));
    }
    //获取节点下所有控件值
    this.getWebControls = function (element, keyValue) {
        var $ele = $(element);
        var resultObj = {};
        $ele.find("input,select,textarea,.ui-select").each(function (index, item) {
            var $item = $(this);
            if ($item.hasClass("NoPost"))
                return;
            var name = $item.attr("name");
            var type = $item.attr("type");
            switch (type) {
                case "checkbox":
                    resultObj[name] = $item.is(":checked") ? true : false;
                    break;
                case "radio":
                    if ($item.is(":checked"))
                        resultObj[name] = $item.val();
                    break;
                case "select":
                    resultObj[name] = $item.attr("data-value");
                    break;
                case "selectTree":
                    resultObj[name] = $item.attr("data-value");
                    break;
                default:
                    resultObj[name] = $item.val();
                    break;
            }
        });
        return resultObj;
    }
    /**
     * @param addDay int类型，要获取当天日期可传0
     * @param format 返回值格式 可选参数：year(2017)、day(2017-01-01)、minute(2017-01-01 10:10)、second(2017-01-01 10:10:10)
     */
    function doHandleTime(val) {
        if (val < 10) {
            return "0" + val;
        }
        return val;
    }
    this.getTimeStr = function (dateTime, format) {
        var timeObj = null;
        if (dateTime == null || dateTime == "") {
            return "";
        }
        else {
            timeObj = new Date(dateTime);
        }
        var year = timeObj.getFullYear();
        var time = year.toString();
        if (format == "year") {
            return time;
        }
        var month = timeObj.getMonth() + 1;
        month = doHandleTime(month);
        var day = timeObj.getDate();
        day = doHandleTime(day);
        time += "-" + month + "-" + day;
        if (format == "day") {
            return time;
        }
        var hour = timeObj.getHours();
        hour = doHandleTime(hour);
        var minute = timeObj.getMinutes();
        minute = doHandleTime(minute);
        time += " " + hour + ":" + minute;
        if (format == "minute") {
            return time;
        }
        var second = timeObj.getSeconds();
        second = doHandleTime(second);
        time += ":" + second;
        if (format == "second") {
            return time;
        }
    }
    this.open = function (content, end, height, title, cancel) {
        if (!height) {
            height = '380px';
        }
        if (!title) {
            title = '附件上传';
        }
        layer.open({
            type: 2,
            title: title,
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['800px', height],
            content: content,
            end: end,
            cancel: cancel
        });
    }
    this.fileinput = function (selector, ApiUrl) {
        var control = $("#" + selector);
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: "http://117.172.164.150:82/xwuploader/UpLoadAllowAnymous.ashx",//开启ajax上传
            allowedFileExtensions: ['jpg', 'png', 'gif', 'doc', 'docx', 'xls', 'xlsx', ],//支持上传的文件格式
            showUpload: true,//是否显示上传按钮
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式
            //dropZoneEnabled: false,//是否显示拖拽区域
            //minImageWidth: 50, //图片的最小宽度
            //minImageHeight: 50,//图片的最小高度
            //maxImageWidth: 1000,//图片的最大宽度
            //maxImageHeight: 1000,//图片的最大高度
            maxFileSize: 0,//单位为kb，如果为0表示不限制文件大小
            //minFileCount: 0,//最小上传单位
            maxFileCount: 2, //表示允许同时上传的最大文件个数
            enctype: 'multipart/form-data',
            //validateInitialCount: true,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", //图标
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
        }).on("fileuploaded", function (event, data) {
            $("#fileInfo").val(data.response.originalFileName + "|" + data.response.WebPath);
            return;
        }).on('fileerror', function (event, data, msg) {
            var a = data;
        });;
    }
    this.ajax = function (options) {
        var defaultOptions = {
            url: undefined,
            data: undefined,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            cache: true,
            anync: true,
            success: null,
            serverUrlApi1: false
        };
        var _options = $.extend(defaultOptions, options);
        return $.ajax({
            url: (_options.serverUrlApi1 == true ? serverUrlApi1 : serverUrl) + _options.url,
            data: _options.contentType.toLowerCase() === 'application/json' && _options.type.toLowerCase() === 'post' ?
                JSON.stringify(_options.data) : _options.data,
            type: _options.type,
            contentType: _options.contentType,
            cache: _options.cache,
            async: _options.async,
            dataType: _options.dataType,
            success: function (data) {
                if (_options.success)
                    _options.success(data);
                else if (data.Flag != 1) {
                    alert(data.Msg);
                    return;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (_options.error)
                    _options.error();


            },
            beforeSend: function (request) {
                var _userInfo = localStorage.getItem("userInfo");
                if (_userInfo != "null" && _userInfo != "" && _userInfo != undefined) {
                    request.setRequestHeader("Authorization", 'BasicAuth ' + JSON.parse(_userInfo).Token);
                    request.setRequestHeader("ApiToken", JSON.parse(_userInfo).ApiKey);
                }
            },
            complete: function () {
            }
        });
    }
    this.GetQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    this.IsNullOrEmpty = function (name) {
        if (name) return false; else return true;
    }

    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
}();

function getNewCode(typeid, select) {
    var inData = { TypeId: typeid };
    Api.ajax({
        type: "post",
        url: "BaseCodeManager/getDictionaryDataById",
        data: inData,
        dyejuri: false,
        success: function (datas) {
            if (datas.Flag == "1") {
                var d = datas.Data;
                for (var i = 0; i < d.length; i++) {
                    if (i == 0) {
                        $("#" + select).append('<option selected="selected" value="' + d[i].Value + '" >' + d[i].Name + '</option>');
                    } else {
                        $("#" + select).append('<option  value="' + d[i].Value + '" >' + d[i].Name + '</option>');
                    }
                }
            }
        }
    });
}

